import { _decorator, Component, Node, AudioClip, Size, view, Animation, CCInteger, CCString, Script, find } from 'cc';
import { AudioMgr } from './AudioMgr';
import { scoreMgr } from './scoreMgr';
const { ccclass, property } = _decorator;

/**
 * 
 * 敌人公共类
 * 
 */
@ccclass('enemy')
export class enemy extends Component {
    

    // 下降速度
    @property(CCInteger)
    speed: number = 10;

    // 生命值
    @property(CCInteger)
    hp: number = 10;

    // 得分
    @property(CCInteger)
    score: number = 10;

    // 死亡动画
    @property(CCString)
    dieAnimation: string = 'enemy1_die';
    
    @property(AudioClip)
    dieAudio: AudioClip;

    
    // 可视区域
    viewSize: Size;


    myScoreMag: scoreMgr;
    
    start() {
        this.viewSize = view.getVisibleSize()

        this.myScoreMag = find('Canvas/syscontrol/score/score_label/score_value').getComponent(scoreMgr)
    }


    update(deltaTime: number) {
        this.run(deltaTime)
    }

    // run
    run(dt: number) {
        let p = this.node.getPosition()

        p.y -= this.speed * 50 * dt;

        if (p.y < - this.viewSize.height - 200) {
            this.node.destroy()
            return
        }

        this.node.setPosition(p)
    }

    /**
     * 
     * 收到攻击
     * 
     */
    hit(power: number) {
        this.hp -= power
        if(this.hp <= 0) {
            this.die()
        }
    }

    /**
     * 死亡
     */
    die() {

        // 给玩家加分
        this.myScoreMag.addScore(this.score)

        // 播放死亡声音和动画
        AudioMgr.inst.playOneShot(this.dieAudio)

        // 死亡动画
        this.node.getComponent(Animation).play(this.dieAnimation)

        // 停止下落
        this.speed = 0

        // 销毁节点, 等待播放完成后销毁
        this.scheduleOnce(() => this.node.destroy(), 1.2)

    }



}


